<template>
  <div class="sensitive-rule-wrap">
    <common-list>
      <common-search slot="search" @search="handleQuery" @reset="resetQuery">
        <el-form
          :model="queryParams"
          ref="queryForm"
          label-width="65px"
          @submit.native.prevent
          :inline="true"
        >
          <el-form-item label="规则名称" prop="ruleName">
            <common-input
              :verify="false"
              @enter="handleQuery"
              v-model="queryParams.ruleName"
              clearable
            />
          </el-form-item>
          <el-form-item label="规则类型" prop="strategyType">
            <el-select v-model="queryParams.strategyType" clearable>
              <el-option label="全部" :value="null"></el-option>
              <el-option label="正则" :value="0"></el-option>
              <el-option label="关键字" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <!-- <common-dept
            ref="commonDept"
            :currentParent="currentParent"
            @getDeptId="getDeptId"
            @getDeptList="getDeptList"
            @getLoading="getLoading" -->
          <!-- ></common-dept> -->
        </el-form>
      </common-search>
      <div slot="tools">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['apisecurity:sensitiverule:add']"
          >新增
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          v-hasPermi="['apisecurity:sensitiverule:remove']"
          @click="handleDelete"
          :disabled="!showBatch"
          >批量删除
        </el-button>
      </div>
      <common-table
        slot="content"
        v-loading="isLoading"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="规则名称"
          align="left"
          prop="ruleName"
          show-overflow-tooltip
        />
        <el-table-column
          label="匹配规则"
          align="left"
          prop="reg"
          show-overflow-tooltip
        />
        <el-table-column
          label="替换正则/关键字"
          align="left"
          prop="replaceReg"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          label="组织"
          align="left"
          prop="deptName"
          width="180"
          show-overflow-tooltip
        >
        </el-table-column>-->
        <el-table-column label="状态" align="center" width="80px">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 0">启用</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 1"
              >停用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="160px">
          <template slot-scope="scope">
            <el-button type="text" @click="getRulesInfo(scope.row)"
              >详情
            </el-button>
            <el-button
              type="text"
              @click="handleRulesEdit(scope.row)"
              v-hasPermi="['apisecurity:sensitiverule:edit']"
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="handleShake(scope.row)"
              :disabled="scope.row.isDisabledForShake"
              v-hasPermi="['apisecurity:sensitiverule:status']"
            >
              <span v-if="scope.row.status === 1">启用</span>
              <span v-if="scope.row.status === 0">停用</span>
            </el-button>
            <el-button
              type="text"
              @click="handleRulesDelete(scope.row)"
              v-hasPermi="['apisecurity:sensitiverule:remove']"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </common-table>
      <pagination
        slot="pagination"
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!-- 添加或编辑敏感规则对话框 -->
      <common-edit-dialog
        :title="isEdit ? '编辑脱敏规则' : '新增脱敏规则'"
        :visible.sync="isEditDialog"
        @cancel="cancel"
        @submit="submit"
        :buttonLoading="isSaveLoading"
      >
        <el-form
          ref="editForm"
          :model="form"
          :rules="rules"
          label-width="80px"
          @submit.native.prevent
        >
          <el-row :gutter="18">
            <el-col :span="24">
              <el-form-item label="规则类型">
                <el-radio-group
                  v-model="form.strategyType"
                  @change="strategyTypeChange(form.strategyType)"
                >
                  <el-radio :label="0">正则</el-radio>
                  <el-radio :label="1">关键字</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="规则名称" prop="ruleName">
                <common-input
                  v-model="form.ruleName"
                  placeholder="请输入"
                  :maxlength="32"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="测试内容" prop="testContent">
                <common-input
                  type="textarea"
                  :verify="false"
                  :maxlength="1500"
                  v-model="form.testContent"
                  placeholder="多个测试内容用逗号隔开"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <common-add-dept
                ref="commonAddDept"
                :deptListParams="deptListParams"
                @getCheckedDeptId="getCheckedDeptId"
                :deptId="form.deptId"
              ></common-add-dept>
            </el-col> -->
            <el-col :span="24">
              <el-form-item
                v-show="form.strategyType === 0"
                label="敏感规则"
                prop="sensitiveId"
              >
                <el-select
                  v-model="form.sensitiveId"
                  @change="matchChange"
                  clearable
                >
                  <el-option
                    v-for="item in matchList"
                    :key="item.wordId"
                    :label="item.name"
                    :value="item.wordId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                :label="form.strategyType === 0 ? '匹配正则' : '关键字'"
                prop="reg"
              >
                <common-input
                  :verify="false"
                  :disabled="form.strategyType === 0"
                  v-model="form.reg"
                  type="textarea"
                  :maxlength="1500"
                  :placeholder="
                    form.strategyType === 0 ? '请输入' : '多个关键字用逗号隔开'
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="">
                <el-button
                  type="primary"
                  plain
                  @click="manualMatch()"
                  :loading="isMatch"
                >
                  匹配
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="匹配结果" prop="matchingResult">
                <common-input
                  :verify="false"
                  v-model="form.matchingResult"
                  disabled
                  type="textarea"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="脱敏方式"
                prop="replaceMode"
                style="min-width: 750px"
              >
                <el-radio-group
                  v-model="form.replaceMode"
                  @change="replaceModeChange"
                >
                  <el-radio v-show="form.strategyType === 0" :label="0"
                    >默认</el-radio
                  >
                  <el-radio v-show="form.strategyType === 0" :label="1"
                    >分组</el-radio
                  >
                  <el-radio :label="2">混淆</el-radio>
                  <el-radio :label="3">替换</el-radio>
                  <el-radio :label="4">映射</el-radio>
                  <el-radio :label="5">截取</el-radio>
                  <el-radio :label="6">遮蔽</el-radio>
                  <el-radio :label="7">加密</el-radio>
                </el-radio-group>
                <content-tip :tipType="'sensitiverule_content'"></content-tip>
              </el-form-item>
            </el-col>

            <!-- 规则类型为关键字才展示 -->
            <el-col :span="24">
              <el-form-item
                v-show="form.strategyType === 1"
                label="替换类型"
                prop="replaceType"
              >
                <el-radio-group v-model="form.replaceType">
                  <el-radio :label="0">保留前后</el-radio>
                  <el-radio :label="1">保留首位</el-radio>
                  <el-radio :label="2">保留末位</el-radio>
                  <el-radio :label="3">全部替换</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                v-show="
                  form.replaceMode !== 0 &&
                  form.replaceMode !== 2 &&
                  form.replaceMode !== 4 &&
                  form.replaceMode !== 5 &&
                  form.replaceMode !== 6 &&
                  form.replaceMode !== 7
                "
                :label="
                  form.strategyType === 0
                    ? form.replaceMode === 0
                      ? '替换正则'
                      : form.replaceMode === 3
                      ? '替换规则'
                      : '分组正则'
                    : '替换字符'
                "
                prop="replaceReg"
              >
                <common-input
                  :verify="false"
                  v-model="form.replaceReg"
                  type="textarea"
                  :maxlength="1500"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                v-show="form.strategyType === 0 && form.replaceMode === 1"
                label=""
              >
                <el-button
                  type="primary"
                  plain
                  @click="manualGrouping()"
                  :loading="isGroup"
                >
                  分组
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                v-show="form.strategyType === 0 && form.replaceMode === 1"
                label="分组结果"
              >
                <div
                  style="
                    width: 100%;
                    min-height: 100px;
                    background-color: #f5f7fa;
                    border: 1px solid #dcdfe6;
                    color: #c0c4cc;
                    padding: 5px 15px;
                    border-radius: 4px;
                  "
                >
                  <el-checkbox-group v-model="form.groupList">
                    <el-checkbox
                      v-for="(group, index) in form.groupResultList"
                      :label="index + 1"
                      :key="index + 1"
                    >
                      {{ `第${index + 1}组: ${group}` }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="">
                <el-button type="primary" plain @click="manualReplace()">
                  替换
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="脱敏结果">
                <common-input
                  :verify="false"
                  v-model="form.replaceResult"
                  disabled
                  type="textarea"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <common-input
                  type="textarea"
                  v-model="form.remark"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </common-edit-dialog>

      <common-info-dialog
        :visible="isInfoDialog"
        @cancel="infoCancel"
        title="脱敏规则详情"
        :infoLoading="infoLoading"
      >
        <common-info-table>
          <common-info-table-cell label="规则类型"
            >{{ info.strategyType === 0 ? "正则" : "关键字" }}
          </common-info-table-cell>
          <common-info-table-cell label="规则名称"
            >{{ info.ruleName }}
          </common-info-table-cell>
          <common-info-table-cell label="测试内容">
            {{ info.testContent }}
          </common-info-table-cell>
          <!-- <common-info-table-cell label="组织">
            {{ info.deptName }}
          </common-info-table-cell> -->
          <common-info-table-cell label="敏感规则" v-if="isRule">
            {{ info.sensitiveName }}
          </common-info-table-cell>
          <common-info-table-cell
            :label="info.strategyType === 0 ? '匹配规则' : '关键字'"
          >
            {{ info.reg }}
          </common-info-table-cell>
          <common-info-table-cell label="匹配结果"
            >{{ info.matchingResult }}
          </common-info-table-cell>
          <common-info-table-cell label="替换方式"
            >{{ info.replaceModeName }}
          </common-info-table-cell>
          <common-info-table-cell
            label="替换类型"
            v-show="info.strategyType === 1"
          >
            <span v-if="info.replaceType === 0">保留前后</span>
            <span v-if="info.replaceType === 1">保留首位</span>
            <span v-if="info.replaceType === 2">保留末位</span>
            <span v-if="info.replaceType === 3">全部替换</span>
          </common-info-table-cell>
          <common-info-table-cell
            :label="
              info.strategyType === 0
                ? info.replaceMode === 0
                  ? '替换正则'
                  : info.replaceMode === 3
                  ? '替换规则'
                  : '分组正则'
                : '替换字符'
            "
          >
            {{ info.replaceReg }}
          </common-info-table-cell>
          <common-info-table-cell
            label="分组结果"
            v-show="info.strategyType === 0 && info.replaceMode === 1"
          >
            <el-checkbox-group v-model="info.groupList" disabled>
              <el-checkbox
                v-for="(group, index) in info.groupResultList"
                :label="index + 1"
              >
                {{ `第${index + 1}组: ${group}` }}
              </el-checkbox>
            </el-checkbox-group>
          </common-info-table-cell>
          <common-info-table-cell label="替换结果"
            >{{ info.replaceResult }}
          </common-info-table-cell>
          <common-info-table-cell label="描述">
            {{ info.remark }}
          </common-info-table-cell>
        </common-info-table>
      </common-info-dialog>
    </common-list>
  </div>
</template>

<script>
import ContentTip from "../../analysisCenter/log/ContentTip/index.vue";
import BaseList from "@/mixins/BaseList";
import {
  getRolesList,
  getRolesInfo,
  updateRolesStatus,
  deleteRoles,
  addRoles,
  updateRoles,
  getMatchingRoles,
  getValidatingRoles,
  getGroupingRoles,
  getDataSensitiveWords,
} from "@/api/apisecurity/sensitiverule";
import { getSingleArray, getFullDept } from "@/utils/util";

export default {
  components: { ContentTip },
  name: "index",
  mixins: [BaseList],
  data() {
    return {
      singleDeptList: [],
      currentParent: 3,
      infoLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        strategyType: null,
        deptIds: null,
      },
      isLoading: false,
      isSaveLoading: false,
      isEditDialog: false,
      isInfoDialog: false,
      list: [],
      matchList: [],
      total: 0,
      isEdit: false,
      form: {
        id: null,
        strategyType: 0, // 规则类型 0正则 1关键词
        ruleName: "", // 规则名称
        testContent: "", // 测试内容
        sensitiveId: "",
        reg: "", // 匹配规则 / 关键字
        matchingResult: "", // 匹配结果

        replaceMode: 0, // 替换方式 0正常 1分组 2同义替换 (同义替换时不传替换正则)

        replaceType: 0, // 替换类型 0保留前后 1保留首位 2保留末位 3全部替换
        replaceReg: "", // 替换规则 / 替换字符
        replaceResult: "", // 替换结果
        groupResult: "", // 分组结果
        groupList: [], // 分组选中的值
        groupResultList: [],
        remark: "",
        deptId: "",
      },
      info: {
        strategyType: 0, // 规则类型 0正则 1关键词
        ruleName: "", // 规则名称
        testContent: "", // 测试内容
        deptId: "",
        sensitiveId: "",
        reg: "", // 匹配规则 / 关键字
        matchingResult: "", // 匹配结果

        replaceMode: 0, // 替换方式 0正常 1分组

        replaceType: 0, // 替换类型 0保留前后 1保留首位 2保留末位 3全部替换
        replaceReg: "", // 替换规则 / 替换字符
        replaceResult: "", // 替换结果
        groupResult: "", // 分组结果
        groupList: [], // 分组结果
        groupResultList: [],
        remark: "",
        replaceModeName: "",
      },
      rules: {
        ruleName: [
          { required: true, message: "请输入规则名称", trigger: "blur" },
        ],
        testContent: [
          { required: true, message: "请输入测试内容", trigger: "blur" },
        ],
        // deptId: [{ required: true, message: '请选择组织', trigger: 'blur' }],
        sensitiveId: [
          { required: true, message: "请选择敏感规则", trigger: "blur" },
        ],
        reg: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value) {
                callback();
              } else {
                if (this.form.strategyType === 0) {
                  callback(new Error("无匹配正则，请重新选择敏感规则"));
                } else {
                  callback(new Error("请输入关键字"));
                }
              }
            },
            trigger: "blur",
          },
        ],
        matchingResult: [
          { required: true, message: "请先进行规则匹配", trigger: "blur" },
        ],
        replaceReg: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value) {
                if (this.form.replaceMode === 0) {
                  if (this.form.strategyType === 0) {
                    try {
                      new RegExp(value);
                      callback();
                    } catch (e) {
                      callback(new Error("请输入正确的替换正则"));
                    }
                  } else {
                    callback();
                  }
                } else {
                  callback();
                }
              } else {
                if (this.form.replaceMode === 3) {
                  if (this.form.strategyType === 0) {
                    callback(new Error("请输入替换规则"));
                  } else {
                    callback(new Error("请输入替换字符"));
                  }
                } else if (this.form.replaceMode === 1) {
                  callback(new Error("请输入分组正则"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur",
          },
        ],
      },
      isReplace: false,
      isMatch: false,
      isGroup: false,
      deptListParams: [],
      isRule: true,
    };
  },
  methods: {
    replaceModeChange() {
      // console.log(123);
      this.$refs.editForm.clearValidate(["replaceReg"]);
    },
    getLoading() {
      this.isLoading = true;
    },
    // getCheckedDeptId(val) {
    //   this.form.deptId = val;
    // },
    // getDeptList(list) {
    //   this.deptListParams = list;
    //   this.singleDeptList = getSingleArray(list);
    //   this.getList();
    // },
    // getDeptId(val) {
    //   this.queryParams.deptIds = val;
    // },
    // getDeptName(val) {
    //   let dept = this.singleDeptList.find((item) => item.id === val.toString());
    //   if (dept) return getFullDept(dept.fulllabel);
    // },
    getList() {
      this.isLoading = true;
      getRolesList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
              });
              return r;
            }, []);
            // this.list.forEach((item) => {
            //   item.deptName = this.getDeptName(item.deptId || "");
            // });
            this.total = res.total;
          } else {
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    getMatchList() {
      getDataSensitiveWords({ matchType: 1 }).then((res) => {
        this.matchList = res.data.reduce((r, c) => {
          r.push({
            ...c,
            wordId: `${c.wordId}`,
          });
          return r;
        }, []);
      });
    },
    matchChange() {
      let match = this.matchList.find(
        (m) => m.wordId === this.form.sensitiveId
      );
      this.form.reg = match?.sensitiveContent ?? "";
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      // this.$refs.commonDept.clearDept();
    },
    handleAdd() {
      this.isEdit = false;
      this.form.id = null;
      this.isEditDialog = true;
    },
    handleDelete() {
      let ids = this.ids.join(",");
      let index = this.list.findIndex((item) => {
        return ids.includes(item.id) && item.status === 0;
      });

      if (index === -1) {
        this.$GlobalDeleteConfirm(
          "删除敏感规则会同时删除与资产的绑定关系，是否确定删除"
        )
          .then(() => {
            this.deleteRoles(ids);
            if (
              this.queryParams.pageNum > 1 &&
              ids.split(",").length === this.list.length
            ) {
              this.queryParams.pageNum -= 1;
            }
          })
          .catch(() => {});
      } else {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
      }
    },
    getRulesInfo(row) {
      this.detail(row);
    },
    detail(row) {
      this.infoLoading = true;
      this.isInfoDialog = true;
      this.isRule = row.strategyType === 0;
      this.getRoleInfo(row.id)
        .then((res) => {
          this.info.strategyType = res.strategyType;

          let sensitive = this.matchList.find(
            (item) => item.wordId === res.sensitiveId
          );

          this.info.sensitiveName = res.sensitiveName;

          this.info.ruleName = res.ruleName ?? "";
          this.info.testContent = res.testContent ?? "";
          this.info.deptId = res.deptId || "";
          this.info.reg = res.reg ?? "";
          this.info.replaceMode = res.replaceMode ?? 0;
          if (this.info.replaceMode === 0) {
            if (res.strategyType === 0) {
              this.info.replaceModeName = "默认";
            }
          } else if (this.info.replaceMode === 1) {
            if (res.strategyType === 0) {
              this.info.replaceModeName = "分组";
            }
          } else if (this.info.replaceMode === 2) {
            this.info.replaceModeName = "混淆";
          } else if (this.info.replaceMode === 3) {
            this.info.replaceModeName = "替换";
          } else if (this.info.replaceMode === 4) {
            this.info.replaceModeName = "映射";
          } else if (this.info.replaceMode === 5) {
            this.info.replaceModeName = "截取";
          } else if (this.info.replaceMode === 6) {
            this.info.replaceModeName = "遮蔽";
          } else {
            this.info.replaceModeName = "加密";
          }
          this.info.replaceType = res.replaceType ?? 0;
          this.info.replaceReg = res.replaceReg ?? "";
          this.info.remark = res.remark ?? "";

          this.info.groupResult = res.groupResult;
          try {
            this.info.groupResultList = JSON.parse(this.info.groupResult);
          } catch (e) {
            console.log("分组结果转换异常", e);
          }
          this.info.groupList = res.groupList
            ? res.groupList.split(",").map(Number)
            : [];
          this.info.matchingResult = res.matchingResult;
          this.info.replaceResult = res.replaceResult;
          // this.info.deptName = this.getDeptName(res.deptId || "");

          this.infoLoading = false;
        })
        .catch((err) => {
          this.$GlobalErrorConfirm("获取信息失败", err.msg, "重新加载").then(
            () => {
              this.detail(row);
            }
          );
        });
    },
    getRoleInfo(id) {
      return new Promise((resolve, reject) => {
        getRolesInfo({ id }).then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          } else {
            reject(res);
          }
        });
      });
    },
    handleRulesEdit(row) {
      if (row.status === 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        this.isEdit = true;

        this.getRoleInfo(row.id)
          .then((res) => {
            this.form.id = res.id;
            this.form.sensitiveId = res.sensitiveId?.toString();
            this.form.strategyType = res.strategyType ?? 0;
            this.form.ruleName = res.ruleName ?? "";
            this.form.testContent = res.testContent ?? "";
            this.form.deptId = res.deptId || "";
            this.form.reg = res.reg ?? "";
            this.form.replaceMode = res.replaceMode ?? 0;
            this.form.replaceType = res.replaceType ?? 0;
            this.form.replaceReg = res.replaceReg ?? "";
            this.form.remark = res.remark ?? "";
            this.form.groupList = res.groupList
              ? res.groupList.split(",").map(Number)
              : [];
            this.form.groupResult = res.groupResult;
            this.form.matchingResult = res.matchingResult;
            this.form.replaceResult = res.replaceResult;

            try {
              this.form.groupResultList = JSON.parse(this.form.groupResult);
            } catch (e) {
              console.log("分组结果转换异常: ", e);
              console.log("groupResult: ", this.form.groupResult);
              this.form.groupResultList = [];
            }

            this.isEditDialog = true;
          })
          .then((err) => {
            console.log("err: ", err);
          });
      }
    },
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        updateRolesStatus({
          id: row.id,
          status: row.status,
        })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage(
                `${row.status === 0 ? "操作" : "操作"}成功`
              );
              resolve(res);
              this.getList();
            } else {
              this.$GlobalErrorConfirm(
                `${row.status === 0 ? "操作" : "操作"}失败`,
                res.msg
              );
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    handleRulesDelete(row) {
      if (row.status === 0) {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
      } else {
        this.$GlobalDeleteConfirm(
          "删除脱敏规则会同时删除与脱敏策略的绑定关系，是否确定删除"
        )
          .then(() => {
            this.deleteRoles(row.id);
          })
          .catch(() => {});
      }
    },
    deleteRoles(id) {
      deleteRoles({
        ids: id,
      }).then((res) => {
        if (res && res.code === 200) {
          this.$GlobalSuccessMessage("删除成功");
          if (
            this.queryParams.pageNum > 1 &&
            ids.split(",").length === this.list.length
          ) {
            this.queryParams.pageNum -= 1;
          }
          this.getList();
        } else {
          this.$GlobalErrorConfirm(`删除失败`, res.msg);
        }
      });
    },
    strategyTypeChange(row) {
      if (row === 1) {
        this.form.replaceMode = 2;
      } else {
        this.form.replaceMode = 0;
      }
      this.clearFormValidate();
    },
    clearFormValidate() {
      if (this.$refs.editForm) this.$refs.editForm.clearValidate();
    },
    resetForm() {
      this.form.id = null;
      this.form.strategyType = 0; // 规则类型 0正则 1关键词
      this.form.ruleName = ""; // 规则名称
      this.form.testContent = ""; // 测试内容
      this.form.deptId = "";
      this.form.sensitiveId = "";
      this.form.reg = ""; // 匹配规则 / 关键字
      this.form.matchingResult = ""; // 匹配结果

      this.form.replaceMode = 0; // 替换方式 0正常 1分组

      this.form.replaceType = 0; // 替换类型 0保留前后 1保留首位 2保留末位 3全部替换
      this.form.replaceReg = ""; // 替换规则 / 替换字符
      this.form.groupList = []; // 分组结果
      this.form.replaceResult = ""; // 替换结果
      this.form.groupResult = ""; // 分组结果
      this.form.remark = "";

      this.form.groupResultList = [];

      this.clearFormValidate();
    },
    cancel() {
      this.resetForm();
      this.isEditDialog = false;
    },
    infoCancel() {
      this.isInfoDialog = false;
    },
    submit() {
      let rules = ["ruleName", "testContent", "reg"];

      if (this.form.strategyType === 0) {
        // 正则
        if (this.form.replaceMode === 1 || this.form.replaceMode === 3) {
          rules = rules.concat(["sensitiveId", "replaceReg"]);
        } else {
          rules = rules.concat(["sensitiveId"]);
        }
      } else {
        if (this.form.replaceMode === 3) {
          rules = rules.concat(["replaceReg"]);
        }
        // 关键字
      }

      this.validateField("editForm", rules)
        .then(() => {
          // 规则类型 规则名称 测试内容 匹配正则/关键字 匹配结果 替换正则/分组正则/替换字符 替换结果 备注

          let params = {
            strategyType: this.form.strategyType,
            ruleName: this.form.ruleName,
            testContent: this.form.testContent,
            deptId: this.form.deptId,
            reg: this.form.reg,
            matchingResult: this.form.matchingResult,
            replaceResult: this.form.replaceResult,
            remark: this.form.remark,
          };
          // 替换方式为同义时 不需要 replaceReg
          if (this.form.replaceMode !== 1 && this.form.replaceMode !== 3) {
            params.replaceMode = this.form.replaceMode;
            params.replaceReg = "";
          } else {
            params.replaceReg = this.form.replaceReg;
          }

          if (this.form.strategyType === 0) {
            // 正则
            // 敏感规则id   替换方式
            // sensitiveId replaceMode

            params.sensitiveId = this.form.sensitiveId;
            params.replaceMode = this.form.replaceMode;

            if (this.form.replaceMode === 0) {
              // 正常 不分组
            } else if (this.form.replaceMode === 1) {
              let groupList =
                this.form.groupList && this.form.groupList.length
                  ? this.form.groupList.join(",")
                  : "";

              params.groupResult = this.form.groupResult;
              params.groupList = groupList;
            }
          } else {
            params.replaceMode = this.form.replaceMode;
            params.replaceType = this.form.replaceType;
          }
          this.isSaveLoading = true;
          if (this.isEdit) {
            params.id = this.form.id;
            // console.log(params);
            updateRoles(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.isSaveLoading = false;
                this.cancel();
              });
          } else {
            addRoles(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.isSaveLoading = false;
                this.cancel();
              });
          }
        })
        .catch(() => {});
    },

    validateField(formName, fields) {
      const commonValidate = (field) => {
        return new Promise((resolve, reject) => {
          if (this.$refs[formName]) {
            this.$refs[formName].validateField(field, (errorMessage) => {
              if (errorMessage) {
                reject();
              } else {
                resolve();
              }
            });
          } else {
            console.error("validateField error: this.$refs[formName] is null");
            reject();
          }
        });
      };

      const fns = fields.reduce((r, c) => {
        r.push(commonValidate(c));
        return r;
      }, []);

      return new Promise((resolve, reject) => {
        Promise.all(fns)
          .then(() => {
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },

    /**
     * 1. 匹配
     */
    manualMatch(cb) {
      this.clearFormValidate();

      this.validateField("editForm", ["ruleName", "testContent", "reg"])
        .then(() => {
          this.isMatch = true;
          getMatchingRoles({
            strategyType: this.form.strategyType,
            ruleName: this.form.ruleName,
            testContent: this.form.testContent,
            reg: this.form.reg,
          })
            .then((res) => {
              if (res && res.code === 200) {
                this.form.matchingResult = res.data.matchList.join(",");
                if (cb) cb();
              } else {
                this.$GlobalErrorConfirm("匹配失败", res.msg);
              }
            })
            .finally(() => {
              this.isMatch = false;
            });
        })
        .catch(() => {});
    },
    /**
     * 2. 分组
     */
    manualGrouping(cb) {
      this.clearFormValidate();

      this.validateField("editForm", [
        "ruleName",
        "testContent",
        "reg",
        "replaceReg",
        "matchingResult",
      ])
        .then(() => {
          this.isGroup = true;
          getGroupingRoles({
            replaceReg: this.form.replaceReg,
            matchingResult: this.form.matchingResult,
          })
            .then((res) => {
              if (res && res.code === 200) {
                this.form.groupResultList = res.data.reduce((r, c) => {
                  r.push(c.join(","));
                  return r;
                }, []);
                this.form.groupResult = JSON.stringify(res.data);
                if (cb) cb();
              } else {
                this.$GlobalErrorConfirm("分组失败", res.msg);
              }
            })
            .finally(() => {
              this.isGroup = false;
            });
        })
        .catch(() => {});
    },
    /**
     * 3. 替换
     */
    manualReplace() {
      this.clearFormValidate();
      let formRules = [];
      if (this.form.replaceMode === 1 || this.form.replaceMode === 3) {
        formRules = [
          "ruleName",
          "testContent",
          "reg",
          "replaceReg",
          "matchingResult",
        ];
      } else {
        formRules = ["ruleName", "testContent", "reg", "matchingResult"];
      }
      this.validateField("editForm", formRules)
        .then(() => {
          this.isReplace = true;
          getValidatingRoles({
            strategyType: this.form.strategyType,
            ruleName: this.form.ruleName,
            testContent: this.form.testContent,
            reg: this.form.reg,
            replaceReg:
              this.form.replaceMode === 1 || this.form.replaceMode === 3
                ? this.form.replaceReg
                : "",
            replaceType: this.form.replaceType,
            replaceMode: this.form.replaceMode,
            groupList: this.form.groupList.join(","),
          })
            .then((res) => {
              if (res && res.code === 200) {
                this.form.replaceResult = res.data.list.join(",");
              } else {
                this.$GlobalErrorConfirm("替换失败", res.msg);
              }
            })
            .catch((err) => {
              console.log("err:", err);
            })
            .finally(() => {
              this.isReplace = false;
            });
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
  },
  mounted() {
    this.getList();
    this.getMatchList();
  },
};
</script>

<style scoped lang="scss"></style>
